package com.xinqi.modules.sys.dict.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.core.utils.StringUtils;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.sys.dict.convert.DictStageConvert;
import com.xinqi.modules.sys.dict.convert.DictVersionConvert;
import com.xinqi.modules.sys.dict.domain.DictStageEntity;
import com.xinqi.modules.sys.dict.domain.DictVersionEntity;
import com.xinqi.modules.sys.dict.dto.req.AddStageDTO;
import com.xinqi.modules.sys.dict.dto.req.DictVersionCreateDTO;
import com.xinqi.modules.sys.dict.dto.req.DictVersionDeleteDTO;
import com.xinqi.modules.sys.dict.dto.req.DictVersionQueryDTO;
import com.xinqi.modules.sys.dict.dto.req.DictVersionUpdateDTO;
import com.xinqi.modules.sys.dict.dto.rsp.DictStageResultDTO;
import com.xinqi.modules.sys.dict.dto.rsp.DictVersionResultDTO;
import com.xinqi.modules.sys.dict.manager.DictStageManager;
import com.xinqi.modules.sys.dict.manager.DictVersionManager;
import com.xinqi.modules.sys.dict.manager.DictVersionStageManager;
import com.xinqi.modules.sys.dict.service.DictVersionService;
import com.xinqi.modules.sys.textbook.manager.CloudTextbookInfoManager;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 字典-版本服务层实现
 *
 * @author: linkai
 * @date: 2023/05/07
 */
@Validated
@Service("dictVersionService")
@RequiredArgsConstructor
public class DictVersionServiceImpl implements DictVersionService {
    private final DictVersionConvert dictVersionConvert;
    private final DictVersionManager dictVersionManager;

    private final DictStageConvert dictStageConvert;
    private final DictStageManager dictStageManager;
    private final DictVersionStageManager dictVersionStageManager;
    private final CloudTextbookInfoManager cloudTextbookInfoManager;

    /**
     * 分页查询 字典-版本数据
     */
    @Override
    @DS("slaver")
    public PageInfo<DictVersionResultDTO> page(Param pageable, DictVersionQueryDTO query) {
        IPage<DictVersionEntity> page = dictVersionManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, dictVersionConvert::convert);
    }

    /**
     * 查询 字典-版本数据
     */
    @Override
    public List<DictVersionResultDTO> find(DictVersionQueryDTO query) {
        return dictVersionManager.list(wrapper(query)).stream()
            .map(dictVersionConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<DictVersionEntity> wrapper(DictVersionQueryDTO query) {
        LambdaQueryWrapper<DictVersionEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(DictVersionEntity::getId, v));
        Queries.accept(query.getName(), v -> wrapper.like(DictVersionEntity::getName, v));
        wrapper.orderByAsc(DictVersionEntity::getSort);
        return wrapper;
    }

    /**
     * 根据id查询 字典-版本数据
     */
    @DS("slaver")
    @Override
    public DictVersionResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(dictVersionManager.findById(id)).map(s -> {
            DictVersionResultDTO convert = dictVersionConvert.convert(s);
            convert.setStageIdList(dictVersionStageManager.findStageByVersionId(id));
            return convert;
        }).orElse(null);
    }

    /**
     * 新增 字典-版本数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid DictVersionCreateDTO dto) {
        DictVersionEntity entity = dictVersionConvert.create(dto);
        dictVersionManager.save(entity);
        dictVersionStageManager.addStage(entity.getId(), dto.getStageIdList());
        return entity.getId();
    }

    /**
     * 根据id修改 字典-版本数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid DictVersionUpdateDTO dto) {
        Optional.ofNullable(dictVersionManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        DictVersionEntity entity = dictVersionConvert.update(dto);
        dictVersionStageManager.addStage(entity.getId(), dto.getStageIdList());
        return dictVersionManager.updateById(entity);
    }

    /**
     * 根据id删除 字典-版本数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return dictVersionManager.removeById(id);
    }

    /**
     * 根据id删除 字典-版本数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(DictVersionDeleteDTO dto) {
        return deleteById(dto.getId());
    }

    /**
     * 通过版本ID获取学段
     */
    @DS("slaver")
    @Override
    public List<DictStageResultDTO> findStageByVersionId(Long id) {
        return dictVersionStageManager.findStageByVersionId(id);
    }

    /**
     * 通过通过版本ID 获取 云课本绑定学段数据
     */
    @DS("slaver")
    @Override
    public List<DictStageResultDTO> findBindStageByVersionId(Long versionId) {
        List<Long> ids = cloudTextbookInfoManager.findByVersionIdList(versionId);
        LambdaQueryWrapper<DictStageEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DictStageEntity::getId, ids);
        List<DictStageEntity> list = dictStageManager.list(wrapper);
        return dictStageConvert.convert(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addStage(@Valid AddStageDTO dto) {
        return dictVersionStageManager.addStage(dto.getVersionId(), dto.getStageIdList());
    }

    @Override
    public Boolean isExistName(String name, Long oId) {
        CommonErrors.BAD_REQUEST.check(StringUtils.isNotEmpty(name), "名称不能为空");
        return dictVersionManager.isExistName(name, oId);
    }

}
